package com.sincon.system.service.impl;
import com.sincon.common.core.domain.entity.SysDept;
import java.util.*;
import com.alibaba.fastjson2.JSONObject;
import com.sincon.common.constant.CacheConstants;
import com.sincon.common.constant.Constants;
import com.sincon.common.core.domain.entity.SysRole;
import com.sincon.common.core.domain.entity.SysUser;
import com.sincon.common.core.domain.model.LoginUser;
import com.sincon.common.core.redis.RedisCache;
import com.sincon.common.utils.ServletUtils;
import com.sincon.common.utils.StringUtils;
import com.sincon.common.utils.ip.AddressUtils;
import com.sincon.common.utils.ip.IpUtils;
import com.sincon.common.utils.uuid.IdUtils;
import com.sincon.common.utils.uuid.UUID;
import com.sincon.system.domain.SysUserRole;
import com.sincon.system.mapper.SysRoleMapper;
import com.sincon.system.mapper.SysUserMapper;
import com.sincon.system.mapper.SysUserRoleMapper;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author LaoGao
 */
@Component
public class TokenBilibiliService
{
    private static final Logger log = LoggerFactory.getLogger(TokenBilibiliService.class);

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            try
            {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
                LoginUser user = redisCache.getCacheObject(userKey);
                return user;
            }
            catch (Exception e)
            {
                log.error("获取用户信息异常'{}'", e.getMessage());
            }
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser)
    {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser)
    {
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    public void refreshTokenBilibili(String token, JSONObject userInfo)
    {
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(token);
        redisCache.setCacheObject(userKey, userInfo, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser)
    {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr();
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        System.out.println("本次生成的BILIBILI-TOKEN == [" + token + "]");
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token)
    {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }


    /**
     * 生成BILIBILI扫码登录TOKEN | 根据用户MID
     * @param userInfo
     * @return
     */
    public Object createBilibiliTokenAuth(JSONObject userInfo) {

        String token = IdUtils.fastUUID();
        userInfo.put("token",token);
        Map<String, Object> claims = new HashMap<>();
        /**
         * 判断此MID是否注册过
         * 1.如果没注册过,则默认直接注册一个账号
         *
         * 2.如果注册过 则直接查询用户对象给塞入
         */

        SysUser biliUser = sysUserMapper.selectUserByBilibiliMid(userInfo.getJSONObject("data").getString("mid"));
        if(!ObjectUtils.isNotEmpty(biliUser)){
            SysUser ins = new SysUser();
            ins.setBilibiliMid(userInfo.getJSONObject("data").getString("mid"));
            ins.setDeptId(103L);
            ins.setNickName(userInfo.getJSONObject("data").getString("name"));
            ins.setUserName(userInfo.getJSONObject("data").getString("name"));
            ins.setEmail("");
            ins.setPhonenumber("");
            ins.setSex("？");
            ins.setAvatar(userInfo.getJSONObject("data").getString("face"));
            ins.setPassword(UUID.getRandom().toString());
            ins.setStatus("0");
            ins.setDelFlag("0");
            ins.setLoginIp("0.0.0.0");
            ins.setLoginDate(new Date());
            ins.setDept(new SysDept());
            /**
             * 新增用户默认角色
             */
            SysRole sysRole = sysRoleMapper.selectRoleById(100L);
            List<SysRole> roles = new ArrayList<>();
            roles.add(sysRole);
            ins.setRoles(roles);
            ins.setRoleIds(new Long[0]);
            ins.setPostIds(new Long[0]);
            ins.setRoleId(0L);
            ins.setSearchValue("");
            ins.setCreateBy("");
            ins.setCreateTime(new Date());
            ins.setUpdateBy("");
            ins.setUpdateTime(new Date());
            ins.setRemark("");
            sysUserMapper.insertUser(ins);
            System.out.println("==============用户mid不存在 正在创建用户.........");
            biliUser = ins;
            List<SysUserRole> sysUserRoles = new ArrayList<>();
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(ins.getUserId());
            sysUserRole.setRoleId(100L);
            sysUserRoles.add(sysUserRole);
            sysUserRoleMapper.batchUserRole(sysUserRoles);
            System.out.println("-----------新增用户绑定成功----------");
        }
        claims.put(Constants.USERINFO,biliUser);
        userInfo.put("userInfo",biliUser);
        refreshTokenBilibili(token,userInfo);
        claims.put(Constants.LOGIN_USER_KEY, token);
        claims.put(Constants.BILIBILI_MID,userInfo.getJSONObject("data").getString("mid"));


        return createToken(claims);

    }

}
